package com.test.BlockingQueueTest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

/**
 * Created by yang on 17/3/22.
 */
public class Consumer implements Runnable{
    BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue){
        this.queue = queue;
    }

    // run方法实现取阻塞队列中的手机，请求登录接口获取token-> 打开题目-> 答题-> redo
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
            try {
                for (int i = 0; i < Basic.phones.size(); i++) {
                    String temp = queue.take();
                    System.out.println(temp + " 已被取走");
                    try {
                        if (Test1.choice == 5) {
                            StuRegister.RegisterStuCount(temp);
                        } else {
                            String token = token(temp);
                            if (Test1.choice == 1) {
                                String openHomework = openHomework(token);
                                getAnswer(openHomework);
                                int isAllRight = submit(token);
                                if (isAllRight == 0) {
                                    int random = Math.random() > 0.7 ? 1 : 0;
                                    if (random == 0) {
                                        String wrongList = getWrongList(token);
                                        getRedoAnswer(wrongList);
                                        redoHomework(token);
                                        System.out.println(temp + " 已提交作业 + 订正完成");
                                    } else {
                                        System.out.println(temp + " 已提交作业 + 未订正");
                                    }
                                } else {
                                    System.out.println(temp + " 已提交作业 + 全部正确");
                                }
                                Thread.sleep(5000);

                            } else if (Test1.choice == 2) {
                                String getCEHomework = StuCEHomework.getCEHomework(token);
                                StuCEHomework.getCEAnswer(getCEHomework);
                                int isAllRight = StuCEHomework.putCEAnswer(token);
                                if (isAllRight == 0) {
                                    int random = Math.random() > 0.7 ? 1 : 0;
                                    if (random == 0) {
                                        String wrongList = StuCEHomework.getCEWrong(token);
                                        StuCEHomework.getCEAnswer(wrongList);
                                        StuCEHomework.redoCEWrong(token);
                                        System.out.println(temp + " 已提交作业 + 订正完成");
                                    } else {
                                        System.out.println(temp + " 已提交作业 + 未订正");
                                    }
                                } else {
                                    System.out.println(temp + " 已提交作业 + 全部正确");
                                }
                            } else if (Test1.choice == 3) {
                                String startExam = StuDoExam.startExam(token);
                                StuDoExam.getExamAnswer(startExam);
                                StuDoExam.submitExam(token);
                                System.out.println(temp + " 已提交试卷");
                                Thread.sleep(5000);
                            } else if (Test1.choice == 4) {
                                StuClass.joinClass(token);
                                System.out.println(temp + " 已加入班群" + Test1.doId);
                            }
                        }
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch(InterruptedException e){
                e.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 登录并获取token
    public static String token(String phoneNum) throws Exception{
        String path = Basic.stuApiRoot + "/user/auth/login";
        String baseJson = "{\"source\":\"androidRCStudent\",\"transaction\":\"login\",\"token\":\"\",\"deviceToken\":\"\",\"deviceType\":\"MI_4LTE\",\"deviceVersion\":\"4.4.4\",\"password\":\"15300085107\",\"channel\":\"Knowbox\",\"deviceId\":\"867323021373194\",\"loginName\":\"18610790001\",\"version\":305}";
        JSONObject jsonObject = new JSONObject(baseJson);
        jsonObject.put("loginName", phoneNum);
        String params = "data=" + jsonObject;
        String response = ConnectionTest.sendPost(path, params);
        JSONObject responseJson = new JSONObject(response);
        String token = responseJson.optString("token");
        return token;
    }

    // 打开作业获取作业数据
    public static String openHomework(String token) throws Exception{
        // question-list请求url
        String path = Basic.stuApiRoot + "/homework/once/question-list";
        // 构造question-list请求参数
        String url = path+"?"+"token="+token+"&homeworkID="+Test1.doId;
        String hwQuestion = ConnectionTest.sendGet(url);
        return hwQuestion;
    }


    // 实现将question-list接口中的作业题目和作业答案分别存放在list中
    public static void getAnswer(String op) throws Exception {
        if (op != null && !op.isEmpty()){
            JSONObject jsonObject = new JSONObject(op);
            JSONArray jsonArray = jsonObject.optJSONArray("questionList");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject quesJson = jsonArray.getJSONObject(i);
                Basic.questionId.add(quesJson.optString("questionID"));
                Basic.rightAnswer.add(quesJson.optString("rightAnswer"));
            }
        }
    }


    // 提交答案
    public static int submit(String token) throws Exception {
        // 定义submit接口请求体中的list
        JSONArray requesList = new JSONArray();
        String path = Basic.stuApiRoot + "/homework/once/commit";
        // 生成随机数，实现部分学生全部答对，部分学生有错题情况
        int random = Math.random() > 0.8 ? 1 : 0;
        int isAllRight = 0;
        if ( random == 1) {
            // 拼凑list
            isAllRight = 1;  // 全对情况
            for (int i = 0; i < Basic.questionId.size(); i++) {
                JSONObject requesOne = new JSONObject();
                requesOne.put("questionID", Basic.questionId.get(i));
                requesOne.put("answer", Basic.rightAnswer.get(i));
                requesOne.put("spendTime", "3000");
                requesList.put(requesOne);
            }
        }else {
            isAllRight = 0;  // 有错题情况
            for (int i = 0; i < Basic.questionId.size(); i++) {
                int random1 = Math.random() > 0.2 ? 1 : 0;
                JSONObject requesOne = new JSONObject();
                requesOne.put("questionID", Basic.questionId.get(i));
                if ( random1 == 1){
                    requesOne.put("answer", Basic.rightAnswer.get(i));
                }else {
                    requesOne.put("answer", "A");
                }
                requesOne.put("spendTime", "3000");
                requesList.put(requesOne);
            }
        }
        // 获取答案list
        JSONObject request = new JSONObject();
        request.put("token", token);
        request.put("homeworkID", Test1.doId);
        request.put("source", "iPhoneRCStudent");
        request.put("transaction", "submitHomework");
        request.put("deviceType", "iPhone6");
        request.put("list", requesList);
        ConnectionTest.sendPost(path,request.toString());
        // 清空questionId和rightAnswer
        Basic.questionId.clear();
        Basic.rightAnswer.clear();
        return isAllRight;
    }

    // 获取错题list
    public static String getWrongList(String token) throws Exception {

        String path = Basic.stuApiRoot + "/homework/once/wrong-list";
        String url = path + "?" + "token=" + token + "&homeworkID=" + Test1.doId;
        String reDoHQuestion = ConnectionTest.sendGet(url);
        return reDoHQuestion;
    }

    // 定义错题作业题目list
    public static List<String> redoQuestionId = new LinkedList<>();
    // 定义错题作业答案list
    public static List<String> redoRightAnswer = new LinkedList<>();
    // 获取错题题目和答案分别放入list
    public static void getRedoAnswer(String redoQuestion) throws JSONException {
        redoRightAnswer.clear();
        if ( redoQuestion != null && !redoQuestion.isEmpty()) {
            JSONObject wrongJson = new JSONObject(redoQuestion);
            JSONArray wrongList = wrongJson.optJSONArray("questionList");
            for (int i = 0; i < wrongList.length(); i++) {
                JSONObject wrongOne = wrongList.getJSONObject(i);
                redoQuestionId.add(wrongOne.optString("questionID"));
                redoRightAnswer.add(wrongOne.optString("rightAnswer"));
            }
        }
    }

    // 订正
    public static void redoHomework(String token) throws Exception {
        // 定义redo-commit接口请求体重的list
        JSONArray redoAnswer = new JSONArray();
        String path = Basic.stuApiRoot + "/homework/once/redo-commit";
        for (int i = 0; i < redoQuestionId.size(); i++) {
            int random = Math.random() > 0.7 ? 1 : 0;
            JSONObject redoJson  = new JSONObject();
            redoJson.put("questionID", redoQuestionId.get(i));
            if ( random == 1){
                redoJson.put("answer", redoRightAnswer.get(i));
            }else {
                redoJson.put("answer", "A");
            }
            redoJson.put("spendTime", "3000");
            redoAnswer.put(redoJson);
        }

        JSONObject redoRequest = new JSONObject();
        redoRequest.put("token", token);
        redoRequest.put("homeworkID", Test1.doId);
        redoRequest.put("list", redoAnswer);
        ConnectionTest.sendPost(path, redoRequest.toString());
        // 清空redoQuestionId和redoRightAnswer
        redoQuestionId.clear();
        redoRightAnswer.clear();
    }
}
